import React, { useTransition, useState, useMemo } from 'react'

export default function UseTransition() {
    // useTransition 过渡hook可以处理页面中同时渲染多个dom 的情况, 对其进行性能优化
    // 01:
    const [isPending, startTransition] = useTransition()
    //console.log(isPending, startTransition);
    // false  startTransition函数

    //02: 定义 进度条的值,以及修改方法
    const [rangeValue, setRangeValue] = useState(0)
    // 03: 
    const [renderData, setRenderData] = useState([])
    // 04: false , 修改状态的方法
    const [isStartTransition, setIsStartTransition] = useState(false)
    console.log(isStartTransition, setIsStartTransition);
    const handleChange = (e) => {
        // 100
        setRangeValue(e.target.value)
        const arr = []
        arr.length = e.target.value
        for (let i = 0; i <= arr.length; i++) {
            arr.fill(i, i + 1)
        }
        if (isStartTransition) {
            // 开启useTransition 的效果, 渲染arr这个DOM数组更快点
            startTransition(() => {
                setRenderData(arr)
            })
        } else {
            // 不开启 useTransition,渲染arr这个DOM数组慢一点
            setRenderData(arr)
        }
    }
    const jsx = useMemo(() => {
        return renderData.map((item, index) => {
            return (
                <div
                    style={{
                        width: 50,
                        height: 50,
                        backgroundColor: `#${Math.floor(Math.random() * 16777215).toString(
                            16
                        )}`,
                        margin: 10,
                        display: 'inline-block',
                    }}
                    key={'item' + index}
                >
                    {item}
                </div>
            )
        })
    }, [renderData])
    return (
        <div>
            <div style={{ textAlign: 'center' }}>
                <label>
                    <input
                        type="checkbox"
                        checked={isStartTransition}
                        onChange={(e) => {
                            setIsStartTransition(e.target.checked)
                        }}
                    />
                    useTransition
                </label>
                <input
                    type="range"
                    value={rangeValue}
                    min={0}
                    max={10000}
                    style={{ width: 120 }}
                    onChange={handleChange}
                />
                <span>进度条 {rangeValue}</span>
                <hr />
            </div>
            {jsx}
        </div>
    )
}